//
//  WJAudioView.m
//  WJBSApp
//
//  Created by dllo on 16/7/21.
//  Copyright © 2016年 王景伟. All rights reserved.
//

#import "WJAudioView.h"
#import "WJEssAndNewModel.h"
#import "BelowView.h"
#import "WJDataManager.h"

@interface WJAudioView ()

// video 和 audio 的三个东西
@property (nonatomic, retain) WJBaseButton *middenBut;

@property (nonatomic, retain) UILabel *playLable;

@property (nonatomic, retain) UILabel *durationLable;

@property (nonatomic, retain) id progressObserver;

@property (nonatomic, assign) CGFloat totalTime;

@property (nonatomic, retain) NSString *strUrl;

@property (nonatomic, assign) BOOL isPlay;


@end

@implementation WJAudioView

-(void)dealloc
{
    [_middenBut release];
    [_playLable release];
    [_durationLable release];
    [_textProgressView release];
    [_model release];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [self.player removeTimeObserver:self.progressObserver];
    [self removeObserverFromPlayerItem:self.player.currentItem];
    [super dealloc];
}

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
       
        [self createView];
        [self createPlayView];
    }
    return self;
}

- (void)createView
{
    self.userInteractionEnabled = YES;
    // 这个是圆圈圈
    self.textProgressView = [[DALabeledCircularProgressView alloc] init];
    // 头变成圆的
    self.textProgressView.roundedCorners = YES;
    [self addSubview:self.textProgressView];
    self.textProgressView.hidden = YES;
    self.textProgressView.progressTintColor = [UIColor orangeColor];
    [_textProgressView release];
    
    
    self.playLable = [[UILabel alloc]init];
    self.playLable.backgroundColor = [UIColor colorWithRed:29/255.0 green:29/255.0 blue:29/255.0 alpha:0.8];
    [self addSubview:self.playLable];
    self.playLable.textColor = [UIColor whiteColor];
    self.playLable.font = [UIFont systemFontOfSize:15];
    [_playLable release];
    
    self.durationLable = [[UILabel alloc]init];
    self.durationLable.backgroundColor = [UIColor colorWithRed:29/255.0 green:29/255.0 blue:29/255.0 alpha:0.8];
    [self addSubview:self.durationLable];
    self.durationLable.textColor = [UIColor whiteColor];
    self.durationLable.font = [UIFont systemFontOfSize:15];
    [_durationLable release];
    
}

- (void)createPlayView
{    
#pragma mark - 创建 播放按钮
    
    self.middenBut = [WJBaseButton buttonWithType:UIButtonTypeCustom];
    self.middenBut.backgroundColor = [UIColor blackColor];
    self.middenBut.alpha = 0.8;
    self.middenBut.layer.cornerRadius = 30;
    self.middenBut.layer.masksToBounds = YES;
    [self.middenBut setImage:[UIImage imageNamed:@"publish-audio@3x副本"] forState:0];
    [self.middenBut addTarget:self action:@selector(playAction:) forControlEvents:1<<6];
    [self addSubview:self.middenBut];
    
    
#pragma Mark- 创建下面的东西
    self.progressView.userInteractionEnabled = YES;
    self.progressView = [[BelowView alloc]init];
    self.progressView.hidden = YES;
    self.progressView.backgroundColor = [UIColor lightGrayColor];
    [self.progressView.playBtn addTarget:self action:@selector(playBut:) forControlEvents:1<<6];
    [self addSubview:self.progressView];
#pragma mark - 创建播放层
    
    //创建playerItem   创建播放器层
   

}


- (void)setModel:(WJEssAndNewModel *)model
{
    if (_model !=model) {
        [_model release];
        _model = [model retain];
    }
    
    
    self.playLable.text = [NSString stringWithFormat:@"%ld次播放", (long)model.audioModel.playcount];
    
    //设置时间格式
    NSInteger min = model.audioModel.duration / 60;
    NSInteger sec = model.audioModel.duration % 60;
    self.durationLable.text = [NSString stringWithFormat:@"%02zd:%02zd",min,sec];
    
    
    [self sd_setImageWithURL:[NSURL URLWithString:self.model.audioModel.thumbnail[0]] placeholderImage:nil options:0 progress:^(NSInteger receivedSize, NSInteger expectedSize) {
        
        if ([[WJDataManager shareFMDB] isExistPicName:self.model.audioModel.thumbnail[0]]) {
            
            self.textProgressView.hidden = YES;
            
        }else{
            
            self.textProgressView.hidden = NO;
            
            self.playLable.hidden = YES;
            
            self.middenBut.hidden = YES;
            
            self.durationLable.hidden = YES;
            
            CGFloat proges = 1.0 * receivedSize / expectedSize;
            
            // 显示文字
            NSString *text = [NSString stringWithFormat:@"%.0f%%", proges * 100];
            self.textProgressView.progressLabel.text = [text stringByReplacingOccurrencesOfString:@"-" withString:@""];
            
            //显示进度值
            [self.textProgressView setProgress:proges animated:NO];
        }
        
    } completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
        
        self.textProgressView.hidden = YES;
        
        
        if (self.isPlay) {
            self.middenBut.hidden = YES;
        }else{
            
            self.middenBut.hidden = NO;
        }
        
        self.playLable.hidden = NO;
        
        self.durationLable.hidden = NO;
        
        if (![[WJDataManager shareFMDB] isExistPicName:self.model.audioModel.thumbnail[0]]) {
            
            [[WJDataManager shareFMDB] insertPicName:self.model.audioModel.thumbnail[0]];
            
        }

    }];


}

-(void)layoutSubviews
{
    [super layoutSubviews];
    
    NSInteger newHeight = self.model.audioModel.height * (WIDTH - 20) / self.model.audioModel.width;
    
    NSDictionary *namedic = @{NSFontAttributeName:[UIFont systemFontOfSize:15]};
    CGRect nameRect = [self.playLable.text boundingRectWithSize:CGSizeMake(1000, 20) options:NSStringDrawingUsesLineFragmentOrigin attributes:namedic context:nil];
    self.playLable.frame = CGRectMake(0, newHeight - 20, nameRect.size.width, 20);
    
    NSDictionary *timedic = @{NSFontAttributeName:[UIFont systemFontOfSize:15]};
    CGRect timeRect = [self.durationLable.text boundingRectWithSize:CGSizeMake(1000, 20) options:NSStringDrawingUsesLineFragmentOrigin attributes:timedic context:nil];
    self.durationLable.frame = CGRectMake(WIDTH - 20 - timeRect.size.width, newHeight - 20, timeRect.size.width, 20);
    
    self.middenBut.frame = CGRectMake((WIDTH - 60) / 2, self.bounds.size.height - 50, 60, 60);

    self.textProgressView.frame = CGRectMake(self.bounds.size.width / 2 - 30, self.bounds.size.height / 2 - 30, 60, 60);

    self.progressView.frame = CGRectMake(0, newHeight - 40 , WIDTH - 20, 40);
    
}


- (void)playAction:(WJBaseButton *)button
{
    NSLog(@"点击了");
    
    NSString *str = [NSString stringWithFormat:@"%ld",(long)self.progressView.tag];
    
    [[NSNotificationCenter defaultCenter] postNotificationName:@"点击了音频" object:str];
    
    self.strUrl = self.model.audioModel.audio[0];
    AVPlayerItem *playerItem = [AVPlayerItem playerItemWithURL:[NSURL URLWithString:self.strUrl]];
    _player = [AVPlayer playerWithPlayerItem:playerItem];
    
    AVPlayerLayer *playerLayer = [AVPlayerLayer playerLayerWithPlayer:self.player];
    [self.layer addSublayer:playerLayer];
    
     [self addObserverToPlayItem:self.player.currentItem];
    
    [self.player play];
}

- (void)playBut:(UIButton *)button
{
    if (button.selected == NO) {
        [self.player pause];
        [button setImage:[UIImage imageNamed:@"音乐暂停.png"] forState:0];
        self.isPlay = NO;
    }else{
        [self.player play];
        [button setImage:[UIImage imageNamed:@"音乐播放.png"] forState:0];
        self.isPlay = YES;
    }
    button.selected = !button.selected;
}


/**
 *	给playerItem添加监控对象  KVO
 */
- (void)addObserverToPlayItem:(AVPlayerItem *)playerItem {
    //监控状态属性: 注意AVPlayer也有一个status属性,通过监控它的status也可以获得播放状态
    [playerItem addObserver:self forKeyPath:@"status" options:NSKeyValueObservingOptionNew context:nil];
    //监控网络加载情况属性
    [playerItem addObserver:self forKeyPath:@"loadedTimeRanges" options:NSKeyValueObservingOptionNew context:nil];
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context {
    AVPlayerItem *playerItem = object;
    if ([keyPath isEqualToString:@"status"]) {
        AVPlayerStatus status = [[change objectForKey:@"new"] intValue];
        if (status == AVPlayerStatusReadyToPlay) {
            NSLog(@"正在播放的视频长度:%.2f",CMTimeGetSeconds(playerItem.duration));
            
            self.totalTime = CMTimeGetSeconds(playerItem.duration);
            
            NSString *str = [NSString stringWithFormat:@"%.0f",CMTimeGetSeconds(playerItem.duration)];
            
            NSInteger min = str.integerValue / 60;
            
            NSInteger sec = str.integerValue % 60;
            
            self.progressView.totalDurationLabel.text = [NSString stringWithFormat:@"%02zd:%02zd",min,sec];
            
            //添加各种通知和观察者
            [self addNotification];
            [self addProgressObserver];
            [self addSliderTarget];
        }
    } else if ([keyPath isEqualToString:@"loadedTimeRanges"]) {  //缓存的时间
        NSArray *array = playerItem.loadedTimeRanges;
        CMTimeRange timeRange = [array.firstObject CMTimeRangeValue];//本次缓存时间范围
        float startSeconds = CMTimeGetSeconds(timeRange.start);
        float durationSeconds = CMTimeGetSeconds(timeRange.duration);
        NSTimeInterval totalBuffer = startSeconds + durationSeconds;
        NSLog(@"共缓存: %.2f",totalBuffer);
        
        self.middenBut.hidden = YES;
        self.progressView.hidden = NO;
        
    }
}

#pragma mark - 播放器通知
- (void)addNotification {
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(playbackFinished:) name:AVPlayerItemDidPlayToEndTimeNotification object:self.player.currentItem];
}

- (void)playbackFinished:(NSNotification *)notification {
    NSLog(@"视频播放完成");
}

#pragma mark - 播放进度监控
/**
 *	进度条监控  当前的时间
 */
- (void)addProgressObserver {
    AVPlayerItem *playerItem = self.player.currentItem;
    //这里每秒执行一次
    __block typeof(self) weakSelf = self;
    _progressObserver = [self.player addPeriodicTimeObserverForInterval:CMTimeMake(1.0, 1.0) queue:dispatch_get_main_queue() usingBlock:^(CMTime time) {
        float current = CMTimeGetSeconds(time);
        float total = CMTimeGetSeconds(playerItem.duration);
        NSLog(@"当前已经播放了%.0f",current);
        
        NSString *str = [NSString stringWithFormat:@"%.0f",current];
        
        NSInteger min = str.integerValue / 60;
        
        NSInteger sec = str.integerValue % 60;
        
        weakSelf.progressView.currentTimeLabel.text = [NSString stringWithFormat:@"%02zd:%02zd",min,sec];
        
        if (current) {
            [weakSelf.progressView.timeIntervalProgress setProgress:(current / total) animated:YES];
            [weakSelf.progressView.progressSlider setValue:(current / total) animated:YES];
        }
    }];
}
#pragma mark - slider方法

- (void)addSliderTarget {
    [self.progressView.progressSlider addTarget:self action:@selector(beginHandleSlider:) forControlEvents:UIControlEventTouchDragInside];
    [self.progressView.progressSlider addTarget:self action:@selector(endHandleSlider:) forControlEvents:UIControlEventValueChanged];
}

- (void)beginHandleSlider:(UISlider *)slider {
    AVPlayerItem *playerItem = self.player.currentItem;
    float total = CMTimeGetSeconds(playerItem.duration);
    float current = slider.value * total;
    [self.player seekToTime:CMTimeMakeWithSeconds(current, playerItem.duration.timescale)];
    [self.player pause];
}

- (void)endHandleSlider:(UISlider *)slider {
    [self.player play];
}


- (void)removeObserverFromPlayerItem:(AVPlayerItem *)playerItem {
    [playerItem removeObserver:self forKeyPath:@"status"];
    [playerItem removeObserver:self forKeyPath:@"loadedTimeRanges"];
}











@end
